package com.liuyi.netty.im.lychat.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuyi.rapid.develop.mybatis.EnableRapidMybatis;
import com.liuyi.rapid.develop.objectmapper.ObjectMapperUtil;
import com.liuyi.rapid.develop.tool.resp.Response;
import com.liuyi.rapid.develop.tool.resp.ResponseCall;
import com.liuyi.rapid.develop.web.EnableRapidWeb;
import com.liuyi.rapid.develop.web.config.GlobalWebAdviceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * liuyi-rapid 快速开发配置
 * @author Mr.Fmy
 * @since 2021/12/25
 */
@Configuration
@EnableRapidWeb
@EnableRapidMybatis
@DependsOn("springContext")
public class LiuyiRapidConfig {

    @Autowired
    public LiuyiRapidConfig(ObjectMapper om) {
        ObjectMapperUtil.basicConfig(om);
        ObjectMapperUtil.java8TimeStrConfig(om);
        ObjectMapperUtil.iwEnumConfig(om);
    }

    @Bean
    public GlobalWebAdviceConfig.ExceptionHandler notLoginException() {
        return new GlobalWebAdviceConfig.ExceptionHandler() {
            @Override
            public boolean supper(Exception ex) {
                return ex instanceof NotLoginException;
            }

            @Override
            public ResponseEntity<Response<Void>> handler(Exception ex) {
                NotLoginException exception = (NotLoginException) ex;
                String msg = null;
                if (exception.getType().equals(NotLoginException.NOT_TOKEN)) {
                    msg = "请先进行登录";
                } else if (exception.getType().equals(NotLoginException.INVALID_TOKEN)) {
                    msg = "登录状态异常，请您重新授权";
                } else if (exception.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
                    msg = "登录已过期，请您重新授权";
                } else if (exception.getType().equals(NotLoginException.BE_REPLACED)) {
                    msg = "您的账号在别处登录，如不是本人操作，请及时修改密码";
                } else if (exception.getType().equals(NotLoginException.KICK_OUT)) {
                    msg = "您的账号被管理员强制下线，如有疑问请联系客服";
                } else {
                    msg = "请先进行登录";
                }
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseCall.error(msg));
            }
        };
    }
}
